import * as types from './types'
import store from '../store/store'
import {GetHomeworksApi} from '../../config/api'

//请求homeworks
export const fetch_homeworks = (filter=null, created_at="") => {
    return dispatch => {
        const homework_reducer = store.getState().homework
        if (!homework_reducer.loading) {
            dispatch({type: types.FETCHING_HOMEWORKS})            
            GetHomeworksApi(homework_reducer.current_page, filter, created_at).then((data) => {
                if (data.code === 0) {
                    //通知reducer请求成功
                    dispatch({type: types.FETCH_HOMEWORK_SUCCESS, homeworks: data.homeworks})
                    if (data.homeworks.length < homework_reducer.per) { dispatch({type: types.HOMEWORK_END_OF_PAGE})} //通知reducer已经没有数据了
                } else {
                    //通知reducer请求失败
                    dispatch({type: types.FETCH_HOMEWORK_FAIL})
                }
            }).catch((err) => {
               //通知reducer请求失败
               dispatch({type: types.FETCH_HOMEWORK_FAIL})
            })
        }
       
    }
}

//刷新homeworks
export const refresh_homeworks = (filter=null, created_at="") => {
    return dispatch => {
        const homework_reducer = store.getState().homework
        if (!homework_reducer.loading) {
            dispatch({type: types.REFRESH_HOMEWORKS})
            dispatch(fetch_homeworks(filter, created_at))
        }
     }
}

//更新其中一条homework，从而刷新列表
export const update_homework = (id, param={}) => {
    return {type: types.UPDATE_HOMEWORK, id: id, param: param}
}